<template>
  <!-- <div class="dashboard-container"> -->
  <div class="app-container">
    <el-card class="page-tools">
      <el-row type="flex" justify="space-between">
        <el-col>
          <el-row type="flex" justify="space-between">
            <el-input
              v-model="page.title"
              placeholder="根据用户名搜索"
            ></el-input>

            <el-button
              style="margin-left: 10px"
              size="medium"
              @click="getAllUserPermission"
              >清空</el-button
            >
            <el-button type="primary" size="medium" @click="searchUser"
              >搜索</el-button
            >
          </el-row>
        </el-col>
        <el-col>
          <el-row type="flex" justify="end">
            <el-button
              type="warning"
              @click="showDialog = true"
              icon="el-icon-edit"
              size="small"
              >新增权限组</el-button
            >
          </el-row>
        </el-col>
      </el-row>
      <el-col class="record" style="margin: 20px 0">
        <i class="el-icon-info" />
        <span>{{ `${total}条记录` }} </span>
      </el-col>

      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
      >
        <el-table-column type="selection" width="300"> </el-table-column>

        <el-table-column label="用户名" prop="title" />
        <el-table-column label="日期">
          <template v-slot="{ row }">
            <span> {{ row.update_date | filterTime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="180px">
          <template slot-scope="{ row }">
            <!-- 编辑按钮 -->
            <el-button
              @click="editPermission(row.id)"
              type="primary"
              icon="el-icon-edit"
              circle
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              @click="deletePermission(row.id)"
              type="danger"
              icon="el-icon-delete"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" align="middle" style="height: 80px">
        <el-pagination
          prev-text="上一页"
          next-text="下一页"
          layout="prev, pager, sizes,next,jumper"
          :page-size.sync="page.pagesize"
          :current-page.sync="page.page"
          :total="total"
          :page-sizes="[10, 20, 30, 40]"
          @current-change="getEmployeeList"
          @size-change="getEmployeeList"
        />
      </el-row>
    </el-card>
    <!-- 新增用户权限弹层 -->
    <el-dialog
      :title="userId ? '编辑用户权限' : '添加用户权限'"
      :visible.sync="showDialog"
      @close="closeDialog"
    >
      <!-- 表单 -->
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            style="width: 80%"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="权限组名称" prop="permission_group">
          <el-tree
            :data="data"
            show-checkbox
            node-key="id"
            ref="tree"
            highlight-current
            :props="defaultProps"
            @check="save"
          >
          </el-tree>
        </el-form-item>
      </el-form>

      <!-- footer插槽 -->
      <template v-slot:footer>
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="closeDialog">取消</el-button>
            <el-button type="primary" size="small" @click="addUser"
              >确定</el-button
            >
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { permissionList, add, detail, remove } from '@/api/base/permissions.js'
import { list as meausList } from '@/api/base/menus.js'
export default {
  data () {
    return {
      Idlist: [],
      // 树形结构
      data: [
        {
          id: 1,
          title: '系统菜单和页面权限点',
          childs: [
            {
              id: 4,
              label: '二级 1-1',
              children: [
                {
                  id: 9,
                  label: '三级 1-1-1'
                },
                {
                  id: 10,
                  label: '三级 1-1-2'
                }
              ]
            }
          ]
        }
      ],
      defaultProps: {
        children: 'childs',
        label: 'title'
      },
      // 添加用户权限的弹层
      formData: {
        username: '', // 用户权限姓名,
        permissions: []
      },

      // value: '', // 当前选中选项的值
      // 校验规则
      rules: {
        username: [
          { required: true, message: '用户权限姓名不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '用户权限姓名为1-10位'
          }
        ],
        permission_group: [
          { required: true, message: '权限组名称不能为空', trigger: 'blur' }
        ]
      },
      // 主界面数据
      userId: '',
      // defaultImg,
      showDialog: false,
      loading: false,
      tableData: [],
      page: {
        page: 1, // 当前页码
        pagesize: 20,
        title: ''
      },
      total: 0 // 总数
    }
  },
  created () {
    this.getPermissionList()
    this.getPermissions()
  },
  methods: {
    // 获取所有数据并转树形结构
    async getPermissions () {
      const { data } = await meausList()
      const newData = JSON.stringify(data).replace(/points/g, 'childs')
      // console.log(JSON.parse(newData))

      this.data[0].childs = JSON.parse(newData)
    },
    // 获取所有选中节点的id
    save () {
      const customerRangeId = this.$refs.tree
        .getCheckedNodes(true) // 组件自带
        .map((item) => {
          const json = {
            id: item.id
            // fullName: item.fullName
          }
          return json
        })
      const areaIdList = customerRangeId.map((item, index) => {
        return item.id
      })
      return areaIdList
    },
    // 清空搜索并重新请求所有的用户权限
    async getAllUserPermission () {
      this.page.title = ''
      this.getPermissionList()
    },
    // 搜索用户权限
    async searchUser () {
      if (this.page.title.trim() === '') return
      this.getPermissionList()
    },
    // 删除用户权限
    async deletePermission (id) {
      try {
        await this.$confirm('此操作将永久删除用户 , 是否继续?')
        const data = {
          id: id
        }
        await remove(data)
        this.$message.success('删除用户权限成功')
        this.getPermissionList()
      } catch (error) {
        console.log(error)
      }
    },
    //  编辑用户权限信息
    async editPermission (id) {
      this.userId = id
      this.showDialog = true
      const data = {
        id: this.userId
      }
      // 先进行数据的回显
      const res = await detail(data)
      console.log(res)
      this.formData.username = res.data.title
      this.formData.permissions = res.data.permissions
      // console.log(res.data.permissions)
      // this.$refs.tree.setCheckedKeys(this.formData.permissions, true)
      this.$refs.tree.setCheckedKeys(this.formData.permissions)

      // 点击确定相当于在一次发送添加新用户权限的功能
      // this.addUser(id)
    },
    // 获取当前选中的节点值
    getCheckedNodes (arg) {
      console.log(arg)
    },
    // 添加用户权限 或者 编辑用户权限（）
    async addUser () {
      this.Idlist = this.save()
      const data = {
        title: this.formData.username,
        permissions: this.Idlist
      }
      this.$refs.formRef.validate()
      this.$refs.tree.setCheckedKeys([])
      await add(data)
      this.getPermissionList()
      this.$message(`${this.userId}` ? '编辑用户权限成功' : '新增用户权限成功')
      this.closeDialog()
    },
    //  获取 用户权限列表
    async getPermissionList () {
      this.loading = true
      const {
        data: { counts, list }
      } = await permissionList(this.page)
      this.total = counts
      this.tableData = list
      this.loading = false
    },
    // 关闭新增用户权限的弹层
    closeDialog () {
      this.showDialog = false
      this.formData = {
        username: '' // 用户权限姓名
      }
      this.$refs.formRef.resetFields()
    },
    getEmployeeList () {}
  }
}
</script>

<style scoped lang="scss">
.page-tools {
  margin: 10px 0;
  .record {
    line-height: 34px;
    i {
      margin-right: 5px;
      color: #919398;
    }
    display: inline-block;
    padding: 0px 10px;
    border-radius: 3px;
    background: #f4f4f4;
  }
}
</style>
